import { useSettingStore } from '@/store/bpmnProcess/settingStore'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { is } from 'bpmn-js/lib/util/ModelUtil'

// //////// only in element extends bpmn:Task
export function getACBefore(element): boolean {
  const prefix = useSettingStore().editor.processEngine
  return isAsyncBefore(element.businessObject, prefix)
}
export function setACBefore(element, value: boolean) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  // overwrite the legacy `async` property, we will use the more explicit `asyncBefore`
  modeling.updateModdleProperties(element, element.businessObject, {
    [`${prefix}:asyncBefore`]: value,
    [`${prefix}:async`]: undefined
  })
}

export function getACAfter(element): boolean {
  const prefix = useSettingStore().editor.processEngine
  return isAsyncAfter(element.businessObject, prefix)
}
export function setACAfter(element, value: boolean) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  modeling.updateModdleProperties(element, element.businessObject, {
    [`${prefix}:asyncAfter`]: value
  })
}

export function getACExclusive(element): boolean {
  const prefix = useSettingStore().editor.processEngine
  return isExclusive(element.businessObject, prefix)
}
export function setACExclusive(element, value: boolean) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  modeling.updateModdleProperties(element, element.businessObject, {
    [`${prefix}:exclusive`]: value
  })
}

// ////////////////// helper
// 是否支持异步属性
export function isAsynchronous(element): boolean {
  const prefix = useSettingStore().editor.processEngine
  return is(element, `${prefix}:AsyncCapable`)
}

// Returns true if the attribute 'asyncBefore' is set to true.
function isAsyncBefore(bo, prefix: string): boolean {
  return !!(bo.get(`${prefix}:asyncBefore`) || bo.get(`${prefix}:async`))
}

// Returns true if the attribute 'asyncAfter' is set to true.
function isAsyncAfter(bo, prefix: string): boolean {
  return !!bo.get(`${prefix}:asyncAfter`)
}

// Returns true if the attribute 'exclusive' is set to true.
function isExclusive(bo, prefix: string): boolean {
  return !!bo.get(`${prefix}:exclusive`)
}
